package com.mnb.base.controller;

import com.mnb.base.service.impl.RainfallCalculationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/rainfall")
public class RainfallController {

    private static final Logger logger = LoggerFactory.getLogger(RainfallController.class);

    @Autowired
    private RainfallCalculationService rainfallCalculationService;

    /**
     * 手动触发日降雨量计算
     */
    @GetMapping("/calculate")
    public ResponseEntity<Map<String, Object>> calculateDailyRainfall(
            @RequestParam(required = false)
            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate targetDate) {

        try {
            LocalDate date = targetDate != null ? targetDate : LocalDate.now();
            logger.info("手动触发日降雨量计算，目标日期: {}", date);

            rainfallCalculationService.manualCalculateDailyRainfall(date);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "日降雨量计算已触发");
            response.put("targetDate", date);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("手动触发日降雨量计算时发生错误: {}", e.getMessage(), e);

            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "计算失败: " + e.getMessage());

            return ResponseEntity.status(500).body(response);
        }
    }
}
